using System;
using System.Diagnostics;

namespace MySqlBackUp.Server.Core
{

    public class ProcessHelper
    {
        /// <summary>
        /// 运行进程
        /// </summary>
        /// <param name="process">.net core环境下这里只能写exe .net环境可以直接写文件路径，框架会查找默认程序</param>
        /// <param name="argument">参数</param>
        public static void Run(string process, string argument = null)
        {
            try
            {
                if (string.IsNullOrEmpty(argument))
                    Process.Start(process);
                else
                    Process.Start(process, argument);
            }
            catch (Exception ex)
            {
                Console.WriteLine(process + " " + argument);
                Console.WriteLine(ex);
            }
        }

        /// <summary>
        /// 关闭进程
        /// </summary>
        public static void Kill(int pid)
        {
            try
            {
                var process = Process.GetProcessById(pid);
                if (process != null)
                    process.Kill();
            }
            catch (Exception ex)
            {
                Console.WriteLine("Pid: " + pid);
                Console.WriteLine(ex);
            }
        }

        /// <summary>
        /// 关闭进程
        /// </summary>
        public static void Kill(string name)
        {
            try
            {
                var processes = Process.GetProcessesByName(name);
                foreach (var process in processes)
                    process.Kill();
            }
            catch (Exception ex)
            {
                Console.WriteLine("ProcessName: " + name);
                Console.WriteLine(ex);
            }
        }
    }
}